import { queryLotStats } from "@/api/chkNum";
import { closeLoading, showError, showLoading } from "@/utils/vant";
import useSelYr, { useSelYrRefs } from "../components/All/useSelYr";
import useSelMon from "../components/Moon/useSelMon";
import useSelWk from "../components/Circ/useSelWk";
interface Params {
  start_year?: string | number;
  end_year?: string | number;
  start_month?: string | number;
  start_weekday?: string | number;
}
const useFetchStats = defineStore("fetch-lotStats", () => {
  const { initMonth } = useSelMon();
  const { initYear } = useSelYr();
  const { yearRange } = useSelYrRefs();
  const { initWeek } = useSelWk();

  const resData = ref<Record<string, any>>([]);
  const params = reactive<Params>({
    start_year: "",
    end_year: "",
    start_month: 1,
    start_weekday: 1
  });
  const requiredKeys = ref<(string | number)[]>(["start_year", "end_year"]);
  function updateParams(newParams: Partial<typeof params>) {
    for (const key in newParams) {
      const val = newParams[key as keyof typeof params]!;
      if (key in params) {
        params[key as keyof typeof params] = val;
        if (["start_year", "end_year"].includes(key)) {
          if (key === "start_year") {
            initYear([val, unref(yearRange)[1]]);
          } else if (key === "end_year") {
            initYear([unref(yearRange)[0], val]);
          }
        }
        if (key === "start_month") {
          initMonth(val);
        }
        if (key === "start_weekday") {
          initWeek(val);
        }
      } else {
        console.warn(`Key "${key}" does not exist in params.`);
      }
    }

    fetchHistStats();
  }
  // const FETCH_DELAY = 300;
  async function fetchHistStats(type?: string) {
    try {
      showLoading();
      /*
      resData.value = [];
      const res = await new Promise<Record<string, any>>(resolve => {
        switch (type) {
          case "All":
          case "Moon":
          case "Circ":
            const timer1 = setTimeout(() => {
              clearTimeout(timer1);
              resolve([
                {
                  title: "เลขท้าย 2 ตัว",
                  data: [
                    { count: 11, numbers: ["79", '11', '22'] },
                    { count: 9, numbers: ["85"] },
                    {
                      count: 10,
                      numbers: ["05", "14", "92", "98", "05", "14", "92", "98", '11']
                    },
                    { count: 7, numbers: ["09", "46", "50", "62"] },
                    { count: 7, numbers: ["09", "46", "50", "62"] },
                    { count: 7, numbers: ["09", "46", "50", "62"] },
                    { count: "", numbers: ["81"] }
                  ]
                },
                {
                  title: "เลขหน้า 3 ตัว",
                  data: [
                    { count: 11, numbers: ["79"] },
                    { count: 9, numbers: ["85"] },
                    { count: 8, numbers: ["05", "14", "92", "98"] },
                    { count: 7, numbers: ["09", "46", "50", "62"] },
                    { count: 7, numbers: ["09", "46", "50", "62"] },
                    { count: 7, numbers: ["09", "46", "50", "62"] },
                    { count: "", numbers: ["81"] }
                  ]
                },
                {
                  title: "เลขท้าย 3 ตัว",
                  data: [
                    { count: 11, numbers: ["79"] },
                    { count: 9, numbers: ["85"] },
                    { count: 8, numbers: ["05", "14", "92", "98"] },
                    { count: 7, numbers: ["09", "46", "50", "62"] },
                    { count: 7, numbers: ["09", "46", "50", "62"] },
                    { count: 7, numbers: ["09", "46", "50", "62"] },
                    { count: "", numbers: ["81"] }
                  ]
                }
              ]);
            }, FETCH_DELAY);
            break;
        }
      });
      resData.value = res;*/
      const filteredParams = Object.keys(params).reduce((acc, key) => {
        if (unref(requiredKeys).includes(key as keyof Params)) {
          acc[key as keyof typeof params] = params[key as keyof typeof params];
        }
        return acc;
      }, {} as Record<string, any>);
      const res = await queryLotStats(filteredParams);
      resData.value = res?.data ?? [];
      // console.log(111222, resData.value);
    } catch (error) {
      showError(error);
    } finally {
      closeLoading();
    }
  }
  return { params, resData, updateParams, requiredKeys };
});

export const useFetchStatsRefs = () => storeToRefs(useFetchStats());
export default useFetchStats;
